<template>
  <view class="work-page">
    <view class="temperature">
      <view class="text"> 当前温度°C </view>
      <view class="input">
        <input
          inputmode="decimal"
          @focus="currentFocus = -1"
          :selection-start="0"
          :selection-end="10000"
          v-model="workMainData.real_temperature"
          placeholder="请输入当前温度"
        />
      </view>
      <view class="text"> 当前湿度% </view>
      <view class="input">
        <input
          inputmode="decimal"
          @focus="currentFocus = -1"
          :selection-start="0"
          :selection-end="10000"
          v-model="workMainData.real_humidity"
          placeholder="请输入当前湿度"
        />
      </view>
    </view>
    <uni-table border stripe emptyText="暂无更多数据">
      <uni-tr>
        <uni-th align="center" width="80px">组/位置</uni-th>
        <uni-th align="center" width="80px">采集数据</uni-th>
        <uni-th align="center" width="80px">范围</uni-th>
        <uni-th align="center" width="50px">目标值</uni-th>
      </uni-tr>
      <!-- 表格数据行 -->
      <template v-for="(grp, index) in groupWorksubData" :key="index">
        <uni-tr v-for="(item, i) in grp" :key="i">
          <uni-td
            v-if="item.flag == 0"
            align="center"
            :class="{ trbackground: item.grp.split('#')[1] % 2 == 0 }"
            >{{ item.grp }}/{{ item.position_id[1] }}</uni-td
          >
          <uni-td v-else align="center" :class="{ trbackground: item.grp.split('#')[1] % 2 == 0 }"
            >{{ item.grp }}/{{ item.remark }}</uni-td
          >
          <uni-td
            v-if="item.flag == 0"
            align="center"
            :class="{ active: item.no_pass, trbackground: item.grp.split('#')[1] % 2 == 0 }"
          >
            <input
              :disabled="!worktoolStore.deviceId.currDeviceId || users.includes(currentUser[0])"
              :value="item.decimal ? item.real_value : item.real_value2"
              :inputmode="currInputMode"
              placeholder="请输入"
              :focus="currentFocus === item.id"
              :selection-start="0"
              :selection-end="10000"
              @focus="inputFocus(item, index)"
              @confirm="onConfirm(item, index)"
              @input="
                (e) => {
                  let eValue = Number(e.detail.value)
                  item.decimal ? (item.real_value = eValue) : (item.real_value2 = eValue)
                }
              "
              @blur="onBlur(item, index)"
            />
          </uni-td>
          <uni-td
            v-else
            align="center"
            :class="{ active: item.no_pass, trbackground: item.grp.split('#')[1] % 2 == 0 }"
          >
            <view class="flagView">{{ item.decimal ? item.real_value : item.real_value2 }} </view>
          </uni-td>
          <!-- <uni-td
            v-if="item.flag == 2"
            align="center"
            :class="{ active: item.no_pass, trbackground: item.grp.split('#')[1] % 2 == 0 }"
          >
            <view class="flagView">{{ sumData[index] }} </view>
          </uni-td> -->
          <!-- <uni-td
            v-if="item.flag == 3"
            align="center"
            :class="{ active: item.no_pass, trbackground: item.grp.split('#')[1] % 2 == 0 }"
          >
            <view class="flagView">{{ diffData[index] }} </view>
          </uni-td> -->
          <!-- <uni-td
            v-if="item.flag == 40"
            align="center"
            :class="{ active: item.no_pass, trbackground: item.grp.split('#')[1] % 2 == 0 }"
          >
            <view class="flagView">{{ diffData[index] }} </view>
          </uni-td> -->
          <!-- <uni-td
            v-if="item.flag == 41"
            align="center"
            :class="{ active: item.no_pass, trbackground: item.grp.split('#')[1] % 2 == 0 }"
          >
            <view class="flagView">{{ sumData[index] }} </view>
          </uni-td> -->
          <uni-td
            v-if="item.max_value != 0 || item.max_value2 != 0"
            align="center"
            :class="{ trbackground: item.grp.split('#')[1] % 2 == 0 }"
          >
            <view class="min-max-value">{{
              item.decimal
                ? item.min_value.toFixed(3) + '~' + item.max_value.toFixed(3) + item.value_unit
                : item.min_value2.toFixed(2) + '~' + item.max_value2.toFixed(2) + item.value_unit
            }}</view>
          </uni-td>
          <uni-td v-else align="center" :class="{ trbackground: item.grp.split('#')[1] % 2 == 0 }">
          </uni-td>
          <uni-td align="center" :class="{ trbackground: item.grp.split('#')[1] % 2 == 0 }">
            <view v-if="item.target_value != 0 || item.target_value2 != 0">
              {{
                item.decimal ? item.target_value.toFixed(3) : item.target_value2.toFixed(2)
              }}</view
            >
          </uni-td>
        </uni-tr>
      </template>
    </uni-table>
    <view class="conclude" v-if="flag === 2"
      >单行最大与最小值之差:<text
        :class="{ active: parseFloat(Amax_min) > parseFloat(workMainData.pass_allow) }"
        >{{ Amax_min }}</text
      >,双行最大与最小值之差:<text
        :class="{ active: parseFloat(Bmax_min) > parseFloat(workMainData.pass_allow) }"
        >{{ Bmax_min }}
      </text>
    </view>
  </view>
</template>

<script setup>
import { onShow } from '@dcloudio/uni-app'
import { computed, ref, onMounted, onUnmounted } from 'vue'
//下面与template没有关系的脚本部分
import { useWorkmainStore, useWorksubStore, useWorktoolStore, useUserStore } from '@/stores'
import { apiGetWorksub } from '@/api/apis'
import { dateShow } from '@/utils/utils.js'
import { emitter } from '@/EventBus'
//解决eval安全报错问题
import { Parser } from 'expr-eval'
const parser = new Parser()
const workMain = useWorkmainStore()
const worksubStore = useWorksubStore()
const worktoolStore = useWorktoolStore()
const userStore = useUserStore()
// const props = defineProps({
//   currentUser: Array,
// })
// // worksub数据
const worksubData = ref([])
// 当前work-main数据
const workMainData = ref({})
const workMainId = ref()
//当前使用的设备
// const deviceId = ref({})
// deviceId.value = worktoolStore.deviceId
//当前用户
const currentUser = ref([])
//可放行的用户
const users = ref([])
// 当前聚焦框
const currentFocus = ref(-1)
//当前光标所存储的数据数组[item,index]
const focusData = ref([])
//定义当前deltaData,key=第几组，value为该组两个数据的数组
const deltaData = ref({})
//按组分开的存储变量
const groupWorksubData = ref([])
//两项数据差值动态显示
// const diffData = ref({})
//两项数据和值动态显示
// const sumData = ref({})
//总的平均值
const Amax_min = ref(0)
const Bmax_min = ref(0)
//需要处理数据的个数
const flag = ref(0)
//组数
// const groupNum = ref(0)
//每组数据显示行
// const rowNum = ref(0)
let rowNum = 0
//仅参与计算的行
let dataRow = 0
//计算的行数
let calcRow = 0
//根据decimal返回字符串，real_value还是real_value2
// function calcRealVal() {
//   //获取对应组数的所有real_value的值列表
//   let realValStr = []
//   for (let index = 0; index < groupWorksubData.value.length; index++) {
//     realValStr[index] = groupWorksubData.value[index].map((item) => {
//       let r = item.decimal ? 'real_value' : 'real_value2'
//       // console.log(item[r])
//       return r
//     })
//   }
//   // console.log(realValStr)
//   return realValStr
// }
function deltaGet() {
  //下面是根据remark的公式进行计算
  for (let i = 0; i < worksubData.value.length; i++) {
    //将remark公式转换成数组
    let tokens = []
    //暂存remark公司内容
    let rmk = ''
    //定位在计算行的地方
    if (worksubData.value[i].flag != 0) {
      rmk = worksubData.value[i].remark
      // console.log('rmk', rmk)
      //去除空格字符
      const expr = rmk.replace(/\s+/g, '')
      //将公式的字符串转换成数组
      tokens = expr.split(/([()+\-*/])/).filter((token) => token)
      // console.log('tokens', tokens)
      //存储token对应的position变量值的索引值
      let op = {}
      //查找token对应的position变量值所在的位置
      for (let p = 0; p < tokens.length; p++) {
        for (let j = 0; j < i; j++) {
          if (worksubData.value[j].position_id[1] == tokens[p]) {
            op[p] = j
          }
        }
      }
      // console.log('op', op)
      //将token对于的position变量值替换成实际变量的值
      for (let k = 0; k < tokens.length; k++) {
        if (worksubData.value[op[k]] != null) {
          tokens[k] = worksubData.value[op[k]].decimal
            ? worksubData.value[op[k]].real_value
            : worksubData.value[op[k]].real_value2
        }
      }
      // console.log('t', tokens)
      //将数组转换成字符串
      // console.log(tokens.join(''))
      //按字符串计算
      let evl = parseFloat(Math.abs(parser.evaluate(tokens.join(''))).toFixed(2))
      // console.log(eval(tokens.join('')))
      //将计算结果存储到数据中
      if (worksubData.value[i].decimal) {
        worksubData.value[i].real_value = evl
      } else {
        worksubData.value[i].real_value2 = evl
      }
    }
  }
  //计算所有数据的指标
  if (flag.value == 2) {
    let dataList = []
    worksubData.value.forEach((item) => {
      if (item.flag == 0) {
        dataList.push(item.decimal ? item.real_value : item.real_value2)
      }
    })
    // console.log('datalist', dataList)
    let oddList = []
    let evenList = []
    dataList.forEach((ele, index) => {
      if (index % 2 != 0) {
        oddList.push(ele)
      } else {
        evenList.push(ele)
      }
    })
    // console.log('oddList', oddList)
    // console.log('evenList', evenList)
    let evenMax = Math.max(...evenList)
    let evenMin = Math.min(...evenList)
    let oddMax = Math.max(...oddList)
    let oddMin = Math.min(...oddList)
    Amax_min.value = (evenMax - evenMin).toFixed(2)
    Bmax_min.value = (oddMax - oddMin).toFixed(2)
  }
}
function onBlur(item, index) {
  // console.log('item,index', [item, index])
  let real_val = Number(item.real_value)
  let real_val2 = Number(item.real_value2)
  item.decimal ? (item.real_value = real_val.toFixed(3)) : (item.real_value2 = real_val2.toFixed(2))
  item.datetime_work = dateShow()[0]
  item.datetimeUTC = dateShow()[1]
  item.operator_id = currentUser.value[0]
  item.deviceId = worktoolStore.deviceId.currDeviceId
  deltaGet()
  //如果有范围值max_value,则判断,对于非计算的数据行
  if (item.max_value != 0 || item.max_value2 != 0) {
    if (item.decimal) {
      if (item.real_value < item.min_value || item.real_value > item.max_value) {
        item.no_pass = true
      } else {
        item.no_pass = false
      }
    } else {
      if (item.real_value2 < item.min_value2 || item.real_value2 > item.max_value2) {
        item.no_pass = true
      } else {
        item.no_pass = false
      }
    }
  } else {
    item.no_pass = false
  }
  //当光标离开最后一个数据时，设置统计行的信息
  // let itemid = item.id
  // //获取当前对象数组中item.id=itemid的数组索引号
  // let i = groupWorksubData.value[index].map((itm) => itm.id).indexOf(itemid)
  //设置计算行的数据
  let flagList = groupWorksubData.value[index].map((itm) => itm.flag)
  for (let i = 0; i < flagList.length; i++) {
    if (flagList[i] != 0) {
      groupWorksubData.value[index][i].datetime_work = dateShow()[0]
      groupWorksubData.value[index][i].datetimeUTC = dateShow()[1]
      groupWorksubData.value[index][i].operator_id = currentUser.value[0]
      groupWorksubData.value[index][i].deviceId = worktoolStore.deviceId.currDeviceId
      //如果有范围值max_value,则判断,对于计算的数据行
      if (
        groupWorksubData.value[index][i].max_value != 0 ||
        groupWorksubData.value[index][i].max_value2 != 0 ||
        groupWorksubData.value[index][i].min_value != 0 ||
        groupWorksubData.value[index][i].min_value2 != 0
      ) {
        if (groupWorksubData.value[index][i].decimal) {
          groupWorksubData.value[index][i].no_pass =
            groupWorksubData.value[index][i].real_value >
              groupWorksubData.value[index][i].max_value ||
            groupWorksubData.value[index][i].real_value < groupWorksubData.value[index][i].min_value
        } else {
          groupWorksubData.value[index][i].no_pass =
            groupWorksubData.value[index][i].real_value2 >
              groupWorksubData.value[index][i].max_value2 ||
            groupWorksubData.value[index][i].real_value2 <
              groupWorksubData.value[index][i].min_value2
          // console.log(groupWorksubData.value[index][i].no_pass)
        }
      } else {
        groupWorksubData.value[index][i].no_pass = false
      }
    }
  }
  // updateMainNopass()
}
//光标移到下一个输入框
function onConfirm(item, index) {
  // console.log('item,index', [item, index])
  let itemid = item.id
  //获取当前对象数组中item.id=itemid的数组索引号
  let i = groupWorksubData.value[index].map((itm) => itm.id).indexOf(itemid)
  // console.log(i, [parseInt(dataRow), rowNum, calcRow])
  if (i < rowNum - 1) {
    //当光标在数据行时,光标自动向下移动
    if (i < dataRow - 1) {
      currentFocus.value = groupWorksubData.value[index][i + 1].id
      //当光标位于计算行时,且计算行后还有数据,则跳过计算行,定位在计算行后面的数据行
    } else if (i == dataRow - 1 && rowNum > dataRow + calcRow) {
      currentFocus.value = groupWorksubData.value[index][i + calcRow + 1].id
      //当光标位于计算行时,且计算行后没有数据,则进入下一个组的数据行开始位置
    } else if (i == dataRow - 1 && rowNum == dataRow + calcRow) {
      try {
        index++
        currentFocus.value = groupWorksubData.value[index][0].id
        //下一组没有就回到最开始
      } catch (error) {
        currentFocus.value = groupWorksubData.value[0][0].id
      }
      //当计算行后面有数据时,并且已经跳过计算行,位于第一条数据的后面数据时
    } else if (i > dataRow - 1) {
      currentFocus.value = groupWorksubData.value[index][i + 1].id
    }
    //当光标处于组内最后一行数据时,需要跳转到下一组数据
  } else {
    try {
      index++
      currentFocus.value = groupWorksubData.value[index][0].id
      //下一组没有就回到最开始
    } catch (error) {
      currentFocus.value = groupWorksubData.value[0][0].id
    }
  }
}
// 聚焦变化时事件
function inputFocus(item, index) {
  console.log('inMode', currInputMode.value)
  currentFocus.value = item.id
  focusData.value = [item, index]
}

//worksub.no_pass 更新workmain.no_pass,以便判断是否操作完，并且符合数据范围，可以上传
function updateMainNopass() {
  // console.log('updateMainNopass')
  // console.log(workMainData.value)
  workMainData.value.no_pass = !worksubData.value.every((element) => {
    return !element.no_pass
  })
  //当flag为2时，增加判断Amax_min 并且 Bmax_min 均小于pass_allow
  if (flag.value == 2) {
    workMainData.value.no_pass =
      workMainData.value.no_pass &&
      Amax_min.value <= workMainData.value.pass_allow &&
      Bmax_min.value <= workMainData.value.pass_allow
  }
  // console.log(workMainData.value.no_pass)
}
// onShow(async () => {
//   //获取当前登录用户
//   // currentUser.value = [userStore.userInfo.uid, userStore.userInfo.name]
//   //获取可放行用户
//   // users.value = userStore.userInfo.users
//   // console.log(users.value)
//   // 初始化数据
//   initProces()
//   deltaGet()
// })
onMounted(async () => {
  // emitter.on('onClickBlue', onClickBlue)
  emitter.on('process', processBleData)
  emitter.on('onSendData', onSendData)
  currentUser.value = [userStore.userInfo.uid, userStore.userInfo.name]
  //获取可放行用户
  users.value = userStore.userInfo.users
  initProces()
  deltaGet()
})
function initProces() {
  //获取worksubData
  workMainId.value = worksubStore.currentWorkMainId
  worksubData.value = worksubStore.records[workMainId.value]
  //获取workMainData
  const workMainIndex = workMain.records.findIndex((item) => item.id == workMainId.value)
  workMainData.value = workMain.records[workMainIndex]
  // deviceId.value = worktoolStore.deviceId
  groupWorksubData.value = []
  console.log(workMainData.value)
  console.log(worksubData.value)

  // 获取每组计算行数及总的行数
  let p = 0
  for (let i = 0; i < worksubData.value?.length; i++) {
    if (worksubData.value[i].flag !== 0) {
      p = p + 1
      // 参与计算的数据行数
      // dataRow = parseInt(worksubData.value[i].flag.toString().slice(0, 1))
      // break
    }
    console.log(i, worksubData.value[i].grp)

    if (i > 0 && worksubData.value[i].grp !== worksubData.value[i - 1].grp) {
      //每组的行数
      rowNum = i
      break
    } else {
      rowNum = i + 1
    }
  }
  calcRow = p
  console.log(rowNum, calcRow)
  for (let i = 0; i < worksubData.value?.length; i += rowNum) {
    groupWorksubData.value.push(worksubData.value.slice(i, i + rowNum))
  }
  // console.log('grpWrokSubData', groupWorksubData.value)
  currentFocus.value = groupWorksubData.value[0][0].id
  //获取flag的值
  for (let i = 0; i < worksubData.value.length; i++) {
    if (worksubData.value[i].flag != 0) {
      flag.value = worksubData.value[i].flag
      break
    }
  }
  // console.log('flag', flag.value)
  //计算每组数据行数，即在flag!=0时,前面都视为数据行
  for (let k = 0; k < groupWorksubData.value[0].length; k++) {
    if (groupWorksubData.value[0][k].flag != 0) {
      dataRow = k
      break
    }
  }
  console.log('dataRow', dataRow)
  console.log('rowNum', rowNum)
  console.log('calcRow', calcRow)
}
onUnmounted(() => {
  //关闭WorkHead所发出的事件
  // emitter.off('onClickBlue', onClickBlue)
  emitter.off('process')
  emitter.off('onSendData')
  updateMainNopass()
})
//蓝牙所采集的数据列表，第一项是采集的数据，第二项是单位
const gotValue = ref([])
//input组件inputmode，判断是否跳出软键盘
const currInputMode = computed(() => {
  if (!worktoolStore.notBluedev) {
    console.log('none')
    return 'none'
  } else {
    console.log('decimal')
    return 'decimal'
  }
})
//选中蓝牙后，进行创建连接并采集数据
// function onClickBlue(item) {
//   clickBlue(item, processBleData)
// }
function onSendData() {
  // sendData(processBleData, currentFocus.value, currInputMode.value)
  emitter.emit('sendData', [currentFocus.value, currInputMode.value])
}
//下面是采集数据后的处理，需要根据当前具体组件的内容重写
function processBleData(getValue) {
  let value = getValue[0]
  let unit = getValue[1]
  console.log('processBleData', value)
  let item = focusData.value[0]
  let index = focusData.value[1]
  if (item.decimal) {
    item.real_value = value.toFixed(3)
    console.log('real_value', item.real_value)
  } else {
    item.real_value2 = value.toFixed(2)
    console.log('real_value2', item.real_value2)
  }
  item.datetime_work = dateShow()[0]
  item.datetimeUTC = dateShow()[1]
  item.operator_id = currentUser.value[0]
  item.deviceId = worktoolStore.deviceId.currDeviceId
  if (item.decimal) {
    if (item.real_value < item.min_value || item.real_value > item.max_value) {
      item.no_pass = true
    } else {
      item.no_pass = false
    }
  } else {
    if (item.real_value2 < item.min_value2 || item.real_value2 > item.max_value2) {
      item.no_pass = true
    } else {
      item.no_pass = false
    }
  }
  //updateMainNopass()
  // deltaGet(item, index)
  onConfirm(item, index)
}
</script>

<style lang="scss" scoped>
.work-page {
  .margin-top-bottom {
    margin: 10px 0;
  }
  .trbackground {
    background-color: #e3e3e1;
  }
  .flagView {
    font-style: italic;
    font-weight: 700;
  }
  // .temperature {
  //   display: flex;
  //   flex-direction: row;
  //   justify-content: center;
  //   width: 100%;
  //   .text {
  //     font-size: 12px;
  //     font-weight: 700;
  //     color: blueviolet;
  //     width: 70px;
  //   }
  //   .input {
  //     width: 30px;
  //   }
  // }
  .temperature {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center; // 添加垂直居中
    flex-wrap: wrap; // 允许换行
    width: 100%;
    gap: 10px; // 添加间距
    padding: 10px 0; // 添加上下内边距

    .text {
      font-size: 12px; // 增大字体
      font-weight: 700;
      color: blueviolet;
      white-space: nowrap; // 防止文字换行
    }

    .input {
      width: 50px; // 增加输入框宽度

      input {
        width: 100%;
        height: 36px;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        padding: 0 8px;
        box-sizing: border-box;
        background-color: #fff;

        &:focus {
          border-color: #1598fa;
          outline: none;
        }
      }
    }
  }
  .conclude {
    margin-top: 5px;
    width: 100%;
    text-align: center;
    font-size: 14px;
  }
  .check {
    background-color: #e0ffff;
  }
  .header {
    display: flex;
    flex-direction: column;
    align-items: center;
    border-bottom: 1px solid $border-color;
    &-prd_name {
      font-size: $text-font-size-m;
      color: $text-font-color-2;
    }
  }
  .active {
    color: #e64340;
  }
  .err-text {
    font-size: $text-font-size-s !important;
    color: $uni-color-error;
  }
  .photo {
    // width: 50px;
    // height: 70px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin: 0 auto;
    // .icon {
    //   padding: 6px;
    //   background: #f0f0f0;
    //   :deep(.uni-icons) {
    //     font-size: 18px !important;
    //   }
    // }
    .button {
      display: flex;
      flex-direction: row;
      justify-items: center;
      &-photo {
        padding: 6px;
        font-size: $text-font-size-s;
        color: $button-color;
      }
      &-delete {
        @extend .button-photo;
        color: $button-err;
      }
    }
  }
  .button-all {
    color: $button-color;
  }
  // .signature {
  //   margin: 10px;
  // }
  .collect-data-popup {
    margin: 10px;
    min-height: 40vh;
    &-title {
      padding: 10px;
      display: flex;
      justify-content: space-between;
      font-weight: 700;
      border-bottom: 1px solid $border-color;
    }
    .add-data {
      padding: 10px;
      font-size: $text-font-size-m;
      color: $button-color;
    }
    .delete-data {
      color: $button-color;
    }
    &-bottom {
      display: block;
      margin: 14px 0;
      padding: 2px 0;
    }
  }
  .document_image {
    width: fit-content;
    margin: 20px auto;
  }
  .checked {
    //border: 1px solid $brand-theme-color;
    background: rgba(194, 219, 239, 0.2);
  }
}
</style>
